package ar.edu.unlam.tpfinal.struts.actions;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import ar.edu.unlam.tpfinal.result.ProcessResult;
import ar.edu.unlam.tpfinal.service.TransactionTypeService;
import ar.edu.unlam.tpfinal.service.exceptions.ServiceException;
import ar.edu.unlam.tpfinal.struts.forms.TransactionTypeForm;

public class TransactionTypeSaveAction extends Action {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
								 HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		TransactionTypeForm transactionTypeForm = (TransactionTypeForm)form;
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		TransactionTypeService tts = (TransactionTypeService) context.getBean("transactionTypeService");
		ProcessResult processResult = validate(transactionTypeForm);
		if(!processResult.isError()){
			processResult = tts.saveTransactionType(transactionTypeForm);
		}
		if(processResult.isError()){
			transactionTypeForm.setErrors(processResult.getProcessError());
			request.setAttribute("transactionTypeForm", transactionTypeForm);
			return mapping.findForward("failure");
		}
		
		List<TransactionTypeForm> transactionTypeFormList = tts.listTransactionType();
		
		request.setAttribute("transactionTypeList", transactionTypeFormList);
		
		if(processResult.isError()){
			request.setAttribute("errors", processResult.getProcessError());	
		} else {
			request.setAttribute("errors", "");
		}
		
		return mapping.findForward("success");
	}

	private ProcessResult validate(TransactionTypeForm transactionTypeForm) {
		ProcessResult processResult = new ProcessResult(); 
		if(transactionTypeForm.getName() == null || transactionTypeForm.getName().equals("")){
			processResult.addProcessError("El nombre no puede ser vacio", new ServiceException("El nombre no puede ser vacio"));
			return processResult;
		}
		if(transactionTypeForm.getRequirements() == null || transactionTypeForm.getRequirements().equals("")){
			processResult.addProcessError("Los requisitos no pueden ser vacios", new ServiceException("Los requisitos no pueden ser vacios"));
			return processResult;
		}
		return processResult;
	}
}
